import { defineStore } from 'pinia'
import request from '../utils/request'

export const useMenuStore = defineStore('menu', {
  state: () => ({ menus: [] }),
  actions: {
    async load() {
      try {
        const { data } = await request.get('/api/menus', { params: { page: 1, size: 1000, sortBy: 'sortOrder', sortOrder: 'asc' } })
        const flat = (data.data?.records || []).map(m => ({
          id: m.id,
          parentId: m.parentId,
          name: m.name,
          path: m.path || '/dashboard',
          icon: m.icon || 'Menu',
          children: []
        }))
        const map = new Map(flat.map(i => [i.id, i]))
        const roots = []
        flat.forEach(i => {
          if (i.parentId && map.has(i.parentId)) {
            map.get(i.parentId).children.push(i)
          } else {
            roots.push(i)
          }
        })
        this.menus = roots
        return roots
      } catch (error) {
        console.error('Failed to load menus:', error)
        // 返回默认菜单结构
        const defaultMenus = [
          {
            id: 0,
            parentId: null,
            name: '首页',
            path: '/dashboard',
            icon: 'House',
            children: []
          },
          {
            id: 1,
            parentId: null,
            name: '系统管理',
            path: '/system',
            icon: 'Setting',
            children: [
              {
                id: 11,
                parentId: 1,
                name: '用户管理',
                path: '/users',
                icon: 'User',
                children: []
              },
              {
                id: 12,
                parentId: 1,
                name: '角色管理',
                path: '/system/roles',
                icon: 'UserFilled',
                children: []
              },
              {
                id: 13,
                parentId: 1,
                name: '菜单管理',
                path: '/system/menus',
                icon: 'Menu',
                children: []
              },
              {
                id: 14,
                parentId: 1,
                name: '管理员管理',
                path: '/system/admins',
                icon: 'Avatar',
                children: []
              }
            ]
          }
        ]
        this.menus = defaultMenus
        return defaultMenus
      }
    },
    buildRoutes(tree) {
      const views = {
        '/users': () => import('../views/Users.vue'),
        '/dashboard': () => import('../views/Dashboard.vue'),
        '/system/roles': () => import('../views/Roles.vue'),
        '/system/menus': () => import('../views/Menus.vue'),
        '/system/admins': () => import('../views/Admins.vue'),
      }
      function dfs(nodes) {
        if (!nodes || !Array.isArray(nodes)) {
          return []
        }
        const rs = []
        nodes.forEach(n => {
          // 确保节点对象存在且有效
          if (n && typeof n === 'object' && n !== null) {
            // 只处理有具体路径的菜单项（非父菜单）
            if (n.path && typeof n.path === 'string' && n.path !== '/system') {
              const route = {
                path: n.path,
                component: views[n.path] || (() => import('../views/Placeholder.vue')),
                meta: { 
                  title: n.name || 'Unknown', 
                  icon: n.icon || 'Menu' 
                }
              }
              rs.push(route)
            }
            // 递归处理子菜单
            if (n.children && Array.isArray(n.children) && n.children.length > 0) {
              const childRoutes = dfs(n.children)
              rs.push(...childRoutes)
            }
          }
        })
        return rs
      }
      return dfs(tree || this.menus)
    }
  }
})


